﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CWCS.Core.Library.SocketManager
{
    public class CommonHelper
    {
        private NewtonsoftJsonSerializer serial;

        public NewtonsoftJsonSerializer BuildCommonJson()
        {
            serial = new NewtonsoftJsonSerializer();
            return serial;
        }

        public string Serialize(object obj, ref bool b_result)
        {
            b_result = false;
            try
            {
                if (obj == null)
                    return "参数不能为空";
                string m_result = BuildCommonJson().Serialize(obj);
                b_result = true;
                return m_result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        /// <summary>Deserialize a json string to an object.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public object Deserialize(string value, Type type, ref bool b_Result, ref string error)
        {
            b_Result = false;
            error = "";
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    error = "value参数为空";
                    return null;
                }
                object obj = BuildCommonJson().Deserialize(value, type);
                b_Result = true;
                return obj;

            }
            catch (Exception ex)
            {
                error = "json转object时发生异常，" + ex.Message;
            }
            return null;
        }
        /// <summary>Deserialize a json string to a strong type object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public T Deserialize<T>(string value, ref bool b_Result, ref string error) where T : class
        {
            b_Result = false;
            error = "";
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    error = "value参数为空";
                    return null;
                }
                T obj = BuildCommonJson().Deserialize<T>(value);
                b_Result = true;
                return obj;

            }
            catch (Exception ex)
            {
                error = "json转T时发生异常，" + ex.Message;
            }
            return null;
        }

    }
}
